package com.hhq.core;

import java.io.*;
import java.net.*;

/**
 * @author 霍华骑
 * @apiNote 继承自Thread，单独处理一个连接的线程
 */
public class DealThread extends Thread {

    private Socket socket;
    private boolean isRun = true;

    public DealThread(Socket ss) {
        this.socket = ss;
        try {
            this.socket.setSoTimeout(10*60*1000); // 10 分钟过时
            this.socket.setKeepAlive(true);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        
    }

    @Override
    public void run() {
        InputStream socInput=null;
        OutputStream socOutput = null;
        try {
            socInput = socket.getInputStream();
            socOutput = socket.getOutputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.out.println("[begin]接收到一个新请求");
        isRun = true;
        while (isRun) {
            try {
                byte[] buf = new byte[100];
                int len = 0;
                StringBuffer sb = new StringBuffer();
                do {
                    len = socInput.read(buf);
                    if (len == -1)
                        break;
                    // System.out.println("len: " + len);
                    sb.append(new String(buf, 0, len, "UTF-8"));
                } while (len == 100 || len == 0);
                if(len == -1){
                   break;
                }
                System.out.println("recv:" + sb.toString());

                // 封装请求报文为Req对象
                String reqBody = sb.toString();
                if (reqBody.length() > 20) {
                    Req req = new Req(sb.toString());
                   
                    // 发送相应
                    Res res = new Res();
                    Controller.controller(req, res); // 控制器处理req请求，并且生成res结果
                    res.headers.put("Connection", "keep-alive");
                    byte[] arr= res.toBytes();
                    System.out.println("返回的报文是：" + res.toString());
                    //  
                    int i=0, blk=1024*256;
                    while( i < arr.length ){
                        int realblk = Math.min( arr.length - i , blk );
                        socOutput.write(arr, i, realblk);
                        socOutput.flush();
                        i = i+blk;
                    } 
                }else{
                    System.out.println("头长不足20");
                }
                System.out.println("deal one connect END\n");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("// 退出连接");
                break; 
            }
        }
        try {
            socOutput.close();
            socInput.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}